using System;
using Gtk;
using System.Data;

namespace Serpis
{
	public class ComboBoxHelper
	{
		//**	Declaramos el evento 'Changed' como publico	
		public event EventHandler Changed;
		
		private ComboBox comboBox;
		



		private IDbCommand dbCommand;
		private IDataReader dataReader;
		private ListStore listStore;
		
		
		public ComboBoxHelper(ComboBox comboBox, IDbConnection dbConnection, string commandText)
		{
			this.comboBox = comboBox;
			dbCommand = AppDbConnection.Instance.DbConnection.CreateCommand();
			dbCommand.CommandText = commandText;
		}

		public string Id
		{
			get
			{
				if(comboBox.Active == -1)
				{
					return "";
				}
				TreeIter treeIter;
				comboBox.GetActiveIter(out treeIter);
				return comboBox.Model.GetValue(treeIter, 0).ToString();
			}
			set
			{
				if(listStore == null)
				{
					dataReader = dbCommand.ExecuteReader();
					listStore = new ListStore(typeof(string), typeof(string));
					CellRendererText cellRendererText = new CellRendererText();
					comboBox.PackStart(cellRendererText, true);
					comboBox.AddAttribute(cellRendererText, "text", 1);
					
					comboBox.Model= listStore;
				
					TreeIter treeIter= TreeIter.Zero;
					while(dataReader.Read()) {
						TreeIter current= listStore.AppendValues(dataReader.GetValues());
						if(dataReader.GetValue(0).ToString() == value)
							treeIter= current;
					}
					if(!treeIter.Equals(TreeIter.Zero))
						comboBox.SetActiveIter(treeIter);
					
					comboBox.Changed += delegate 
					{
						raiseChanged();
					};
								
					dataReader.Close();					
				}
				else
				{
					TreeIter treeIter;
					comboBox.Model.GetIterFirst(out treeIter);
					do
					{
						if(comboBox.Model.GetValue(treeIter, 0).ToString() == value) 
						{
							comboBox.SetActiveIter(treeIter);
							break;
						}
					}
					while(comboBox.Model.IterNext(ref treeIter));					
				}
			}
		}
		private void raiseChanged() 
		{
			if(Changed != null)
			{
				Changed(this, EventArgs.Empty);
			}
		}

	}
}

